class Confirm {
    static container = null;
    static activeConfirm = null;

    static show(options) {
        // 关闭已存在的确认框
        if (this.activeConfirm) {
            this.close();
        }

        // 初始化容器
        if (!this.container) {
            this.container = document.createElement('div');
            this.container.className = 'confirm-container';
            document.body.appendChild(this.container);
        }

        // 处理参数，新增 modal 配置项（默认 true，即模态框）
        const config = {
            title: '确认',
            message: '确定要执行此操作吗？',
            confirmText: '确定',
            cancelText: '取消',
            onConfirm: () => { },
            onCancel: () => { },
            modal: true, // 新增：是否为模态框（true 时点击遮罩不关闭）
            ...options
        };

        // 创建 Confirm 元素
        const confirm = document.createElement('div');
        confirm.className = 'confirm';

        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'confirm-overlay';

        // 插入完整的 DOM 结构
        confirm.innerHTML = `
            <div class="confirm-content">
                <div class="confirm-header">
                    <h3 class="confirm-title">${config.title}</h3>
                </div>
                <div class="confirm-body">
                    <p class="confirm-message">${config.message}</p>
                </div>
                <div class="confirm-footer">
                    <button class="confirm-button confirm-cancel">${config.cancelText}</button>
                    <button class="confirm-button confirm-primary">${config.confirmText}</button>
                </div>
            </div>
        `;

        // 添加到容器
        this.container.appendChild(overlay);
        this.container.appendChild(confirm);
        this.activeConfirm = { confirm, overlay, config };

        // 强制重绘，确保动画能正确触发
        void confirm.offsetHeight;

        // 触发显示动画
        overlay.classList.add('show');
        confirm.classList.add('show');

        // 绑定事件
        const primaryBtn = confirm.querySelector('.confirm-primary');
        const cancelBtn = confirm.querySelector('.confirm-cancel');

        const handleConfirm = () => {
            this.close();
            config.onConfirm();
        };

        const handleCancel = () => {
            this.close();
            config.onCancel();
        };

        primaryBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);

        // 根据 modal 配置决定是否绑定遮罩层点击事件
        if (!config.modal) {
            // 非模态框：点击遮罩关闭
            overlay.addEventListener('click', handleCancel);
        } else {
            // 模态框：点击遮罩不关闭（可添加视觉反馈，如轻微震动）
            overlay.addEventListener('click', () => {
                if (config.modal) {
                    // 可选：添加模态框遮罩点击反馈
                    confirm.classList.add('modal-shake');
                    setTimeout(() => {
                        confirm.classList.remove('modal-shake');
                    }, 300);
                }
            });
        }

        // 保存引用以便清理
        confirm._handlers = {
            primaryBtn,
            cancelBtn,
            overlay,
            handleConfirm,
            handleCancel,
            // 保存遮罩层点击事件引用
            overlayClick: config.modal ? null : handleCancel
        };

        return {
            close: () => this.close()
        };
    }

    static close() {
        if (!this.activeConfirm || !this.container) return;

        const { confirm, overlay, config } = this.activeConfirm;
        const { primaryBtn, cancelBtn, handleConfirm, handleCancel, overlayClick } = confirm._handlers;

        // 移除事件监听
        primaryBtn.removeEventListener('click', handleConfirm);
        cancelBtn.removeEventListener('click', handleCancel);

        // 根据 modal 配置移除对应事件
        if (!config.modal && overlayClick) {
            overlay.removeEventListener('click', overlayClick);
        } else {
            // 移除模态框的遮罩点击反馈事件
            overlay.removeEventListener('click', () => { });
        }

        // 触发隐藏动画
        overlay.classList.remove('show');
        confirm.classList.remove('show');
        confirm.classList.add('hide');

        // 动画结束后移除元素
        const onAnimationEnd = () => {
            confirm.removeEventListener('animationend', onAnimationEnd);
            if (overlay.parentNode) overlay.remove();
            if (confirm.parentNode) confirm.remove();

            // 如果容器为空，则移除容器
            if (this.container.children.length === 0) {
                this.container.remove();
                this.container = null;
            }

            this.activeConfirm = null;
        };

        confirm.addEventListener('animationend', onAnimationEnd);

        // 如果没有设置动画，确保元素最终被移除
        setTimeout(onAnimationEnd, 300);
    }
}

export const showConfirm = (options) => Confirm.show(options);
export const closeConfirm = () => Confirm.close();